import os
import uuid
from PIL import Image
from center.tools.imgOperation import generate_folder_path

os.environ.setdefault("DJANGO_SETTINGS_MODULE", "commandCenter.settings")
import django

django.setup()
from center.models import *


def save_image_to_task(task_id, image_path):
    try:
        task = Task.objects.get(pk=task_id)
    except Task.DoesNotExist:
        print(f"Task with id {task_id} not found.")
        return

    # 验证模型字段是否存在
    if not hasattr(task, 'imgs_path'):
        print(f"Task model does not have 'imgs_path' field")
        return
    print(task.get_images_list())
    try:
        # 生成唯一文件名
        ext = os.path.splitext(image_path)[1][1:]  # 获取扩展名
        unique_filename = f"{uuid.uuid4().hex[:8]}.{ext}"

        # 生成动态路径
        folder_path = generate_folder_path(
            task_id=task.id,
            task_name=task.task_name,  # 假设模型有name字段
            release_time=task.release_time  # 假设模型有release_time字段
        )
        # 构建完整存储路径
        full_path = os.path.join('', folder_path, unique_filename)
        abs_path = os.path.join(settings.TASK_IMAGES, full_path)

        # 创建目录（如果不存在）
        os.makedirs(os.path.dirname(abs_path), exist_ok=True)

        # 打开图片
        img = Image.open(image_path)
        # 保存图片到指定路径
        img.save(abs_path)
        print(f"Image saved to: {abs_path}")
    except FileNotFoundError:
        print(f"Image file not found at {image_path}")
    except AttributeError as ae:
        print(f"Missing required field: {str(ae)}")
    except Exception as e:
        print(f"An error occurred: {str(e)}")


# 使用示例
task_id = 3
image_path = 'D:\\d179f883e22957819256a4b6a28eae85.jpg'
save_image_to_task(task_id, image_path)
